<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-form ref="userEditForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="账号" prop="name">
            <el-input v-model="form.name" type="text"/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password"/>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password"/>
          </el-form-item>
          <el-form-item v-show="!isSelf" label="状态" prop="status" placeholder="请选择">
            <el-select v-model="form.status">
              <el-option v-for="item in userStatusEnum" :label="item.text" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :action="uploadUrl"
              :headers="uploadHeaders"
              class="avatar-uploader"
              accept="image/*">
              <img v-if="form.avatar" :src="form.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>

          </el-form-item>
          <el-form-item>
            <el-button @click="save"> 保存</el-button>
            <el-button @click="complete(false)"> 取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import userApi from '@/api/sys/user'
import { getToken } from '@/utils/auth'
import userStatusEnum from '@/enums/user/userStatusEnum'

export default {
  name: 'UserEdit',
  props: {
    id: {
      type: String,
      required: true
    },
    t: {
      type: Number,
      required: true
    },
    self: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    // 验证-密码
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback()
        return
      }
      if (this.form.confirmPassword !== '') {
        this.$refs.userEditForm.validateField('confirmPassword')
      }
      if (value.length < 6 || value.length > 20) {
        callback(new Error('长度在6到20个字符之间'))
        return
      }
      callback()
    }
    // 验证-确认密码
    var validateConfirmPass = (rule, value, callback) => {
      if (this.form.password === '') {
        callback()
        return
      }
      if (value === '') {
        callback(new Error('不能为空'))
        return
      }
      if (value.length < 6 || value.length > 20) {
        callback(new Error('长度在6到20个字符之间'))
        return
      }
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
        return
      }
      callback()
    }
    return {
      // 表单数据
      form: {
        id: this.id,
        name: '',
        password: '',
        status: '',
        confirmPassword: '',
        avatar: ''
      },
      isSelf: this.self,
      roleDialogVisible: false,
      uploadAvatarDialogVisible: false,
      // 状态枚举
      statusEnum: [{
        label: '冻结',
        value: -1
      }, {
        label: '有效',
        value: 1
      }],
      // 验证规则
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPass, trigger: 'blur' }
        ]

      },
      userStatusEnum
    }
  },
  computed: {
    uploadUrl: function() {
      return process.env.BASE_API + '/api/sys/file/upload'
    },
    uploadHeaders: function() {
      var headers = {}
      headers['X-Auth-Token'] = getToken()
      return headers
    }
  },
  watch: {
    t: function(newVal, oldVal) {
      this.form.id = this.id
      this.getUserDetail()
    }
  },
  mounted() {
    this.getUserDetail()
  },
  methods: {
    // 保存数据
    save() {
      // 验证表单数据
      this.$refs.userEditForm.validate((valid) => {
        if (valid) {
          // 验证通过，提交数据
          if (this.isSelf) {
            userApi.editCurrentUser(this.form).then(response => {
              if (response.data.code === 200) {
                this.$message.success('保存成功')
                this.complete(true)
              } else {
                this.$message.error(response.data.msg)
              }
            })
            return
          }
          userApi.editUser(this.form).then(response => {
            if (response.data.code === 200) {
              this.$message.success('保存成功')
              this.complete(true)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
      return
    },
    // 完成事件
    complete(done) {
      // this.closeCurrentTag()
      // this.toList()
      this.$refs.userEditForm.resetFields()
      this.$emit('complete', done)
    },
    // 获取用户信息
    getUserDetail() {
      if (!this.form.id) { return }
      userApi.userDetail(this.form.id).then(response => {
        if (response.data.code === 200) {
          var userInfo = response.data.data
          this.form.name = userInfo.name
          this.form.status = userInfo.status
          this.form.avatar = userInfo.avatar
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.form.avatar = res.data
      }
    },
    beforeAvatarUpload(file) {
      return true
    },
    uploadAvatar(file) {

    }
  }
}
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
